<template>
  <div class="p-2">
    <transition :enter-active-class="proxy?.animate.searchAnimate.enter" :leave-active-class="proxy?.animate.searchAnimate.leave">
      <div class="search" v-show="showSearch">
        <el-form :model="queryParams" ref="queryFormRef" :inline="true" label-width="68px">
          <!-- <el-form-item label="目录id" prop="propertyAssetCatalogId">
            <el-input v-model="queryParams.propertyAssetCatalogId" placeholder="请输入目录id" clearable style="width: 240px" @keyup.enter="handleQuery" />
          </el-form-item>
          <el-form-item label="入库数量" prop="inventoryQuantity">
            <el-input v-model="queryParams.inventoryQuantity" placeholder="请输入入库数量" clearable style="width: 240px" @keyup.enter="handleQuery" />
          </el-form-item>
          <el-form-item label="单价" prop="univalence">
            <el-input v-model="queryParams.univalence" placeholder="请输入单价" clearable style="width: 240px" @keyup.enter="handleQuery" />
          </el-form-item>
          <el-form-item label="合计" prop="total">
            <el-input v-model="queryParams.total" placeholder="请输入合计" clearable style="width: 240px" @keyup.enter="handleQuery" />
          </el-form-item> -->
          <el-form-item label="类别" prop="category">
            <el-select v-model="queryParams.category" placeholder="请选择类别" clearable>
              <el-option v-for="item in categoryData" :key="item.id" :label="item.category" :value="item.id" />
            </el-select>
          </el-form-item>
          <el-form-item label="名称" prop="name">
            <el-input v-model="queryParams.name" placeholder="请输入资产名称" clearable />
          </el-form-item>
          <!-- <el-form-item label="入库时间" prop="storageTime">
            <el-date-picker clearable
              v-model="queryParams.storageTime"
              type="date"
              value-format="YYYY-MM-DD"
              placeholder="请选择入库时间"
            />
          </el-form-item> -->
          <el-form-item>
            <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
            <el-button icon="Refresh" @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-form>
      </div>
    </transition>

    <el-card shadow="never">
      <template #header>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button type="primary" plain icon="Plus" @click="handleAdd" v-hasPermi="['business:assetInventoryRecords:add']">新增</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button
              type="success"
              plain
              icon="Edit"
              :disabled="single"
              @click="handleUpdate()"
              v-hasPermi="['business:assetInventoryRecords:edit']"
              >详情</el-button
            >
          </el-col>
          <el-col :span="1.5">
            <el-button
              type="danger"
              plain
              icon="Delete"
              :disabled="multiple"
              @click="handleDelete()"
              v-hasPermi="['business:assetInventoryRecords:remove']"
              >删除</el-button
            >
          </el-col>
          <!-- <el-col :span="1.5">
            <el-button type="warning" plain icon="Download" @click="handleExport" v-hasPermi="['business:assetInventoryRecords:export']">导出</el-button>
          </el-col> -->
          <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>
      </template>

      <el-table v-loading="loading" :data="assetInventoryRecordsList" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center" />
        <!-- <el-table-column label="资产进库记录id" align="center" prop="id" v-if="true" /> -->
        <!-- <el-table-column label="目录id" align="center" prop="propertyAssetCatalogId" /> -->
        <el-table-column label="类别" align="center" prop="category">
          <template #default="scope">
            <span>{{getCategory(scope.row.category)}}</span>
          </template>
        </el-table-column>
        <el-table-column label="名称" align="center" prop="name" />
        <el-table-column label="型号" align="center" prop="model" />
        <el-table-column label="单位" align="center" prop="unit" />
        <el-table-column label="入库数量" align="center" prop="inventoryQuantity" />
        <el-table-column label="单价" align="center" prop="univalence" />
        <el-table-column label="合计" align="center" prop="total" />
        <el-table-column label="入库时间" align="center" prop="storageTime" width="180">
          <template #default="scope">
            <span>{{ parseTime(scope.row.storageTime, '{y}-{m}-{d}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="备注" align="center" prop="remark" />
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template #default="scope">
            <el-tooltip content="修改" placement="top">
              <el-button
                link
                type="primary"
                icon="Edit"
                @click="handleUpdate(scope.row)"
                v-hasPermi="['business:assetInventoryRecords:edit']"
              ></el-button>
            </el-tooltip>
            <el-tooltip content="删除" placement="top">
              <el-button
                link
                type="primary"
                icon="Delete"
                @click="handleDelete(scope.row)"
                v-hasPermi="['business:assetInventoryRecords:remove']"
              ></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>

      <pagination v-show="total>0" :total="total" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize" @pagination="getList" />
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { listAssetInventoryRecords, getAssetInventoryRecords, delAssetInventoryRecords, addAssetInventoryRecords, updateAssetInventoryRecords } from '@/api/business/assetInventoryRecords';
import { AssetInventoryRecordsVO, AssetInventoryRecordsQuery, AssetInventoryRecordsForm } from '@/api/business/assetInventoryRecords/types';
import router from "@/router";
import { listAssetCategory } from '@/api/business/assetCategory/index';

const { proxy } = getCurrentInstance() as ComponentInternalInstance;

const assetInventoryRecordsList = ref<AssetInventoryRecordsVO[]>([]);
const buttonLoading = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref<Array<string | number>>([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const categoryData = ref([])

const queryFormRef = ref<ElFormInstance>();
const assetInventoryRecordsFormRef = ref<ElFormInstance>();

const dialog = reactive<DialogOption>({
  visible: false,
  title: ''
});

const initFormData: AssetInventoryRecordsForm = {
  id: undefined,
  type:"2",
  propertyAssetCatalogId: undefined,
  category:undefined,
  name:undefined,
  model:undefined,
  unit:undefined,
  inventoryQuantity: undefined,
  univalence: undefined,
  total: undefined,
  storageTime: undefined,
  remark: undefined,
}
const data = reactive<PageData<AssetInventoryRecordsForm, AssetInventoryRecordsQuery>>({
  form: {...initFormData},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    type:"2",
    propertyAssetCatalogId: undefined,
    category:undefined,
    name:undefined,
    model:undefined,
    unit:undefined,
    inventoryQuantity: undefined,
    univalence: undefined,
    total: undefined,
    storageTime: undefined,
    params: {
    }
  },
  rules: {
    id: [
      { required: true, message: "资产进库记录id不能为空", trigger: "blur" }
    ],
    propertyAssetCatalogId: [
      { required: true, message: "目录id不能为空", trigger: "blur" }
    ],
    inventoryQuantity: [
      { required: true, message: "入库数量不能为空", trigger: "blur" }
    ],
    univalence: [
      { required: true, message: "单价不能为空", trigger: "blur" }
    ],
    total: [
      { required: true, message: "合计不能为空", trigger: "blur" }
    ],
  }
});

const { queryParams, form, rules } = toRefs(data);

/** 查询资产进库记录列表 */
const getList = async () => {
  await getfixedCategory()
  loading.value = true;
  const res = await listAssetInventoryRecords(queryParams.value);
  assetInventoryRecordsList.value = res.rows;
  total.value = res.total;
  loading.value = false;
}

/** 取消按钮 */
const cancel = () => {
  reset();
  dialog.visible = false;
}

/** 表单重置 */
const reset = () => {
  form.value = {...initFormData};
  assetInventoryRecordsFormRef.value?.resetFields();
}

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value?.resetFields();
  handleQuery();
}

/** 多选框选中数据 */
const handleSelectionChange = (selection: AssetInventoryRecordsVO[]) => {
  ids.value = selection.map(item => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
const handleAdd = () => {
  /* reset();
  dialog.visible = true;
  dialog.title = "添加资产进库记录"; */
  router.push({ path: '/NotFixedAssetManagement/NotFixedAssetManagementEnter/NotFixedAssetManagementEnterAdd', query: { type:'add' } })
}

/** 修改按钮操作 */
const handleUpdate = async (row?: AssetInventoryRecordsVO) => {
  /* reset();
  const _id = row?.id || ids.value[0]
  const res = await getAssetInventoryRecords(_id);
  Object.assign(form.value, res.data);
  dialog.visible = true;
  dialog.title = "修改资产进库记录"; */
  const _id = row?.id || ids.value[0]
  router.push({ path: '/NotFixedAssetManagement/NotFixedAssetManagementEnter/NotFixedAssetManagementEnterAdd', query: { type:'edit',id:_id } })

}

/** 提交按钮 */
const submitForm = () => {
  assetInventoryRecordsFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      buttonLoading.value = true;
      if (form.value.id) {
        await updateAssetInventoryRecords(form.value).finally(() =>  buttonLoading.value = false);
      } else {
        await addAssetInventoryRecords(form.value).finally(() =>  buttonLoading.value = false);
      }
      proxy?.$modal.msgSuccess("修改成功");
      dialog.visible = false;
      await getList();
    }
  });
}

/** 删除按钮操作 */
const handleDelete = async (row?: AssetInventoryRecordsVO) => {
  const _ids = row?.id || ids.value;
  await proxy?.$modal.confirm('是否确认删除数据项？').finally(() => loading.value = false);
  await delAssetInventoryRecords(_ids);
  proxy?.$modal.msgSuccess("删除成功");
  await getList();
}

/** 导出按钮操作 */
const handleExport = () => {
  proxy?.download('business/assetInventoryRecords/export', {
    ...queryParams.value
  }, `assetInventoryRecords_${new Date().getTime()}.xlsx`)
}

const getCategory = (data) =>{
  if (data && categoryData.value) {
    let obj = categoryData.value.find(item=>item.id ==data)
    return obj?.category
  }
}

const getfixedCategory = async () =>{
  const res = await listAssetCategory();
  categoryData.value = res.rows
  // xztotal.value = res.total;
}

onMounted(async() => {
  // await getfixedCategory()
  await getList();
});
</script>
